package com.xique.door.project.miniprogram.controller;

import com.xique.common.core.domain.R;
import com.xique.common.core.utils.PicUtil;
import com.xique.common.core.utils.SmsUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.web.controller.BaseController;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.door.api.model.LoginAppUser;
import com.xique.door.constant.RedisConstants;
import com.xique.door.project.miniprogram.biz.service.IMiniLoginBizService;
import com.xique.door.util.RedisUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @author shd
 * @create 2022/4/12 16:49
 */
@RestController
@RequestMapping("/login")
public class MiniLoginController extends BaseController {

    @Autowired
    private IMiniLoginBizService loginBizService;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SmsUtils smsUtils;

    @GetMapping("/getPhone")
    public R<String> getPhone(@RequestParam("code") String code) {
        return loginBizService.getPhone(code);
    }

    @PostMapping("")
    public R<LoginAppUser> login(@RequestParam("phone") String phone, @RequestParam("code") String code) {
        return loginBizService.wxLogin(phone, code);
    }

    /**
     * 发送验证码短信
     */
    @GetMapping(value = "/sendSmsCode")
    public R<String> sendAuthCode(@RequestParam("phone") String phone) {
        try {
            AjaxResult result = smsUtils.sendVerificationCodeSms(phone);
            redisUtil.set(RedisConstants.REDIS_DOOR_WX_AUTH_CODE_PREFIX + phone, result.get("randomCode"), 10 * 60);
            return R.ok(result.get("randomCode").toString());
        } catch (Exception e) {
            e.printStackTrace();
            return  R.fail("发送短信失败，请联系管理员！");
        }
    }

    /**
     * 验证码登录
     */
    @PostMapping(value = "/verificationCode")
    public R<LoginAppUser> verificationCode(@RequestParam("phone") String phone, @RequestParam("code") String code) {
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            return  R.fail("手机号验证码必填项不能为空");
        }
        Object o = redisUtil.get(RedisConstants.REDIS_DOOR_WX_AUTH_CODE_PREFIX + phone);
        if (Objects.isNull(o)) {
            return R.fail("验证码已失效，请重新获取");
        }
        if (!code.equals(o.toString())) {
            return  R.fail("验证码错误，请重新获取");
        }
        return loginBizService.phoneLogin(phone);
    }

}
